package com.bw.utils;

import com.alibaba.fastjson.JSONObject;
import com.bw.common.GmallConfig;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtil {

    public static <T> List<T> queryList(Connection connection, String sql, Class<T> clz, boolean underScoreCamel) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 用来装结果
        List<T> resultSet = new ArrayList<>();

        // 创建PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        // 执行
        ResultSet rs = preparedStatement.executeQuery();
        // 获取原数据信息
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        //遍历
        while (rs.next()) {
            // 创建一个实例对象
            T t = clz.newInstance();
            for (int i = 1; i < columnCount + 1; i++) {
                // 取出字段名字 sku_num
                String columnName = metaData.getColumnName(i);
                if (underScoreCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE
                            .to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }

                // 取出字段对应的值  10
                Object object = rs.getObject(columnName);

                BeanUtils.setProperty(t, columnName, object);
            }
            resultSet.add(t);
        }
        //关闭连接
        rs.close();
        preparedStatement.close();
        return resultSet;
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException, InvocationTargetException, InstantiationException, IllegalAccessException {
//        String columnName = "SKU_NUM";
//        columnName = CaseFormat.LOWER_UNDERSCORE
//                .to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
//        System.out.println("columnName = " + columnName);
        Class.forName(GmallConfig.PHOENIX_DRIVER);
        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);
        String user_id = "700";
        String sql = "select * from GMALL2105_REALTIME.DIM_USER_INFO where id = '" + user_id + "'";
//        List<JSONObject> jsonObjects = queryList(connection, sql, JSONObject.class, false);
//        for (JSONObject jsonObject : jsonObjects) {
//            System.out.println("jsonObject = " + jsonObject);
//        }
        System.out.println("sql = " + sql);
    }

}
